#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QRegularExpression>
#include <QDateTime>
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonObject>
#include <QValueAxis>
#include <csignal>  // 添加这个头文件
#include <QNetworkInterface>  // 网络接口相关
#include <QHostAddress>       // IP地址处理
#include <QDebug>
#include <iostream>

void MainWindow::showNetworkConfigDialog()
{
    QDialog dialog(this);
    dialog.setWindowTitle("Network Configuration");

    QFormLayout form(&dialog);

    // 主控板卡配置
    QLineEdit *cameraIpEdit = new QLineEdit(ConfigManager::instance().cameraIP());
    QSpinBox *cameraPortSpin = new QSpinBox();
    cameraPortSpin->setRange(1, 65535);
    cameraPortSpin->setValue(ConfigManager::instance().cameraPort());

    // MCU配置
    QLineEdit *mcuIpEdit = new QLineEdit(ConfigManager::instance().mcuIP());
    QSpinBox *mcuPortSpin = new QSpinBox();
    mcuPortSpin->setRange(1, 65535);
    mcuPortSpin->setValue(ConfigManager::instance().mcuPort());

    // ICS服务端口
    QSpinBox *tcpPortSpin = new QSpinBox();
    tcpPortSpin->setRange(1, 65535);
    tcpPortSpin->setValue(ConfigManager::instance().icstcpPort());

    QSpinBox *cameraUdpSpin = new QSpinBox();
    cameraUdpSpin->setRange(1, 65535);
    cameraUdpSpin->setValue(ConfigManager::instance().icsCameraUdpPort());

    QSpinBox *mcuUdpSpin = new QSpinBox();
    mcuUdpSpin->setRange(1, 65535);
    mcuUdpSpin->setValue(ConfigManager::instance().icsMcuUdpPort());

    QSpinBox *slavePortSpin = new QSpinBox();
    slavePortSpin->setRange(1, 65535);
    slavePortSpin->setValue(ConfigManager::instance().slavePort());

    // 添加控件到表单
    form.addRow("Camera IP:", cameraIpEdit);
    form.addRow("Camera Port:", cameraPortSpin);
    form.addRow("MCU IP:", mcuIpEdit);
    form.addRow("MCU Port:", mcuPortSpin);
    form.addRow("ICS TCP Port:", tcpPortSpin);
    form.addRow("ICS Camera UDP Port:", cameraUdpSpin);
    form.addRow("ICS MCU UDP Port:", mcuUdpSpin);
    // 从板卡配置
    QLineEdit *slaveIpEdits[4];
    for(int i = 0; i < 4; ++i) {
        slaveIpEdits[i] = new QLineEdit(ConfigManager::instance().slaveIp(i));
        form.addRow(QString("Slave %1 IP:").arg(i), slaveIpEdits[i]);
    }
    form.addRow("Slave Port:", slavePortSpin);

    QDialogButtonBox buttonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
                               Qt::Horizontal, &dialog);
    form.addRow(&buttonBox);

    connect(&buttonBox, &QDialogButtonBox::accepted, [&]() {
        // 保存配置
        ConfigManager::instance().setValue("Network", "CameraIP", cameraIpEdit->text());
        ConfigManager::instance().setValue("Network", "CameraPort", cameraPortSpin->value());
        ConfigManager::instance().setValue("Network", "MCUIP", mcuIpEdit->text());
        ConfigManager::instance().setValue("Network", "MCUPort", mcuPortSpin->value());
        ConfigManager::instance().setValue("Network", "ICSTcpPort", tcpPortSpin->value());
        ConfigManager::instance().setValue("Network", "ICSCameraUdpPort", cameraUdpSpin->value());
        ConfigManager::instance().setValue("Network", "ICSMcuUdpPort", mcuUdpSpin->value());

        for(int i = 0; i < 4; ++i) {
            ConfigManager::instance().setValue("Network",
                                               QString("Slave%1IP").arg(i), slaveIpEdits[i]->text());
        }

        ConfigManager::instance().setValue("Network", "SlavePort", slavePortSpin->value());

        QMessageBox::information(this, "Info",
                                 "Network configuration saved. Restart application to apply changes.");
        dialog.accept();
    });

    connect(&buttonBox, &QDialogButtonBox::rejected, &dialog, &QDialog::reject);

    dialog.exec();
}

void MainWindow::on_btnsetmcu_clicked(){
    mcuIp = ui->lineEditMcuIp->text();
    mcuPort = ui->spinBoxMcuPort->value();
    LOG_GENERAL("mcuIp:   " + mcuIp);
    //LOG_GENERAL("mcuPort:   " + std::to_string(mcuPort));
}


void MainWindow::on_btnsetcamera_clicked(){
    cameraIp = ui->lineEditCameraIp->text();
    cameraPort = ui->spinBoxCameraPort->value();
    LOG_CAMERA("cameraIp:   " + cameraIp);
    //LOG_GENERAL("cameraPort:   " + std::to_string(cameraPort));
}

void MainWindow::on_btnBrowsePath_clicked() {
    QString path = QFileDialog::getExistingDirectory(
        this,
        "选择BIN文件存储路径",
        QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)
        );

    if (!path.isEmpty()) {
        binPath = path;
        ui->lineEditBinPath->setText(path);
        LOG_GENERAL("The storage path of BIN has been set to: " + path);
    }
}

void MainWindow::onLoopCheckBoxStateChanged(int state)
{
    // 启用/禁用循环次数选择框
    ui->loopCountSpinBox->setEnabled(state == Qt::Checked);
}


/*
void MainWindow::on_btnStartExposure_clicked() {
    static qint64 lastSendTime = 0;
    qint64 now = QDateTime::currentMSecsSinceEpoch();
    if (now - lastSendTime < 500) return;
    lastSendTime = now;

    if (cameraState.status != 0) {
        LOG_CAMERA("相机当前状态为[%1]，无法开始曝光");
        return;
    }

    // 重置状态
    m_currentExpInfo = ExposureInfo();
    m_currentExpInfo.isManual = true;
    m_currentExpInfo.tag = QDateTime::currentDateTime().toString("yyMMddhhmmss");
    m_currentExpInfo.imageName = ui->lineEditBaseFilename->text();

    if (m_currentExpInfo.imageName.isEmpty()) {
        m_currentExpInfo.imageName = "manual_" + m_currentExpInfo.tag;
    }

    // 收集手动拍摄的头信息
    m_manualKeywords = collectManualHeaderInfo();

    // 如果是本地手动拍摄，自动递增IMG_NUM
    if (!isSequenceRunning) { // 非序列拍摄时
        m_localImageCounter++;
        ui->lineEditImgNum->setText(QString::number(m_localImageCounter));
    }

    // 设置进度条参数
    currentExposureTime = ui->doubleSpinBoxExposureTime->value();
    currentProgressTotalTime = currentExposureTime + 12;
    progressStartTime = QDateTime::currentMSecsSinceEpoch();

    ui->ExposureprogressBar->setRange(0, 100);
    ui->ExposureprogressBar->setValue(0);
    progressTimer->start();

    // 生成唯一标识
    QString tag = QDateTime::currentDateTime().toString("yyMMddhhmmss");
    cameraState.currentTag = tag;

    // 获取参数
    // 获取当前选择的帧类型
    QString frameType = ui->comBoxframetype->currentData().toString();
    int darkMode = (frameType == "bs" || frameType == "dk") ? 1 : 0;
    int pinning = ui->checkBoxPinning->isChecked() ? 1 : 0;
    int dump = ui->checkBoxDump->isChecked() ? 1 : 0;

    // 设置基础文件名
    currentBaseFilename = ui->lineEditBaseFilename->text();
    if (currentBaseFilename.isEmpty()) {
        currentBaseFilename = "manual_" + tag;
    }
    LOG_CAMERA("currentBaseFilename: " + currentBaseFilename);

    // 构建指令
    QString cmd = QString("get_frame_290:$tag=%1$dark=%2$pinning=%3$dump=%4$exp=%5")
                      .arg(tag).arg(darkMode).arg(pinning).arg(dump).arg(currentExposureTime);

    sendCameraCommand(cmd);
    LOG_CAMERA("已发送指令 " + cmd);
    LOG_CAMERA("已启动曝光，任务ID: " + tag);
}*/

void MainWindow::on_btnStartExposure_clicked()
{
    static qint64 lastSendTime = 0;
    qint64 now = QDateTime::currentMSecsSinceEpoch();
    if (now - lastSendTime < 500) return;
    lastSendTime = now;

    if (cameraState.status != 0) {
        LOG_CAMERA("The current status of the camera is [%1]，can not StartExposure");
        return;
    }
    // 重置状态
    m_currentExpInfo = ExposureInfo();
    m_currentExpInfo.isManual = true;
    m_currentExpInfo.tag = QDateTime::currentDateTime().toString("yyMMddhhmmss");
    m_currentExpInfo.imageName = ui->lineEditBaseFilename->text();

    if (m_currentExpInfo.imageName.isEmpty()) {
        m_currentExpInfo.imageName = "manual_" + m_currentExpInfo.tag;
    }
    // 获取当前选择的帧类型
    QString frameType = ui->comBoxframetype->currentData().toString();
    int darkMode = (frameType == "bs" || frameType == "dk") ? 1 : 0;

    // 保存到当前曝光信息中
    m_currentExpInfo.darkMode = darkMode;
    m_currentExpInfo.frameType = frameType;

    // 获取当前读出速度
    int rateIndex = ui->comboBoxReadoutRate->currentData().toInt();
    QString readoutRate = readoutRateMap.value(rateIndex, "Unknown");

    // 保存到当前曝光信息中
    m_currentExpInfo.readoutRate = readoutRate;

    // 收集手动拍摄的头信息
    m_manualKeywords = collectManualHeaderInfo();

    // 如果是本地手动拍摄，自动递增IMG_NUM
    if (!isSequenceRunning) { // 非序列拍摄时
        m_localImageCounter++;
        ui->lineEditImgNum->setText(QString::number(m_localImageCounter));
    }

    static int currentLoop = 0;
    static int totalLoops = 1;
    static ExposureInfo loopExposureInfo;

    // 如果是第一次启动或新循环
    if(currentLoop == 0 && ui->loopCheckBox->isChecked()) {
        totalLoops = ui->loopCheckBox->isChecked() ? ui->loopCountSpinBox->value() : 1;

        // 保存当前拍摄参数
        loopExposureInfo = m_currentExpInfo;
        loopExposureInfo.isManual = true;
        loopExposureInfo.tag = QDateTime::currentDateTime().toString("yyMMddhhmmss");

        // 更新进度标签
        ui->labelProgressStatus->setText(
            QString("Loop %1/%2").arg(currentLoop+1).arg(totalLoops));
    }

    // 设置基础文件名
    currentBaseFilename = ui->lineEditBaseFilename->text();
    if (currentBaseFilename.isEmpty()) {
        currentBaseFilename = "manual_" + m_currentExpInfo.tag;
    }
    LOG_CAMERA("currentBaseFilename: " + currentBaseFilename);
    if(ui->loopCheckBox->isChecked()){
        m_currentExpInfo.imageName = QString("%1_loop%2")
        .arg(currentBaseFilename)
            .arg(currentLoop+1, 2, 10, QChar('0'));
    }
    // 设置进度条参数
    //currentProgressTotalTime = currentExposureTime + 12;

    // 初始化进度控制
    currentPhase = PHASE_EXPOSING;
    progressStartTime = QDateTime::currentMSecsSinceEpoch();
    currentExposureTime = ui->doubleSpinBoxExposureTime->value();

    // 设置进度条范围
    ui->ExposureprogressBar->setRange(0, 100);
    ui->ExposureprogressBar->setValue(0);

    // 启动定时器
    progressTimer->start(200); // 200ms更新一次

    // 生成唯一标识
    //QString tag = QString("%1_%2").arg(loopExposureInfo.tag).arg(currentLoop+1, 2, 10, QChar('0'));
    // cameraState.currentTag = tag;
    // 生成唯一标识
    QString tag = QDateTime::currentDateTime().toString("yyMMddhhmmss");
    cameraState.currentTag = tag;

    // 构建指令
    //int darkMode = (ui->comBoxframetype->currentData().toString() == "bs" ||
    //ui->comBoxframetype->currentData().toString() == "dk") ? 1 : 0;
    int pinning = ui->checkBoxPinning->isChecked() ? 1 : 0;
    int dump = ui->checkBoxDump->isChecked() ? 1 : 0;

    QString cmd = QString("get_frame_290:$tag=%1$dark=%2$pinning=%3$dump=%4$exp=%5")
                      .arg(tag).arg(darkMode).arg(pinning).arg(dump).arg(currentExposureTime);

    sendCameraCommand(cmd);
    if(ui->loopCheckBox->isChecked()){
        LOG_CAMERA(QString("Start Loop Exp [%1/%2]").arg(currentLoop+1).arg(totalLoops));
    }

    // 更新循环计数器
    currentLoop++;
    if(currentLoop >= totalLoops && ui->loopCheckBox->isChecked()) {
        currentLoop = 0;
        LOG_CAMERA("Loop Exp completed");
    }
}

/*
void MainWindow::onBrowseFitsFileClicked()
{
    QString fitsFilter = "FITS Images (*.fits *.fit *.fts);;All Files (*)";
    QString filePath = QFileDialog::getOpenFileName(this,
                                                    "Select FITS File",
                                                    QDir::homePath(),
                                                    fitsFilter);

    if(!filePath.isEmpty()) {
        //ui->lineEditFitsFile->setText(filePath);
        launchDS9(filePath);
    }
}*/



void MainWindow::on_btnSetReadoutRate_clicked() {
    // 1. 获取用户选择的档位
    int rateIndex = ui->comboBoxReadoutRate->currentData().toInt();

    // 2. 验证档位有效性
    if (!readoutRateMap.contains(rateIndex)) {
        LOG_CAMERA("Invalid read out rate gear: " + QString::number(rateIndex));
        QMessageBox::warning(this, "error", "Invalid read out rate gear set");
        return;
    }
    // 3. 检查相机状态
    if (!isCameraIdle()) {
        LOG_CAMERA("The camera is busy and cannot set the readout speed.");
        QMessageBox::warning(this, "warning", "The camera is currently busy, please wait for it to be idle.");
        return;
    }
    // 4. 构建并发送指令
    QString cmd = QString("readout_rate_290:$rate=%1").arg(rateIndex);
    sendCameraCommand(cmd);
    sendCommandToSlave(cmd, "192.168.0.101");
    sendCommandToSlave(cmd, "192.168.0.102");
    sendCommandToSlave(cmd, "192.168.0.103");
    sendCommandToSlave(cmd, "192.168.0.104");
    LOG_CAMERA("Readout rate setting command has been sent: " + cmd);
}


void MainWindow::on_btnAbort_clicked() {
    if (cameraState.status == 0) {
       LOG_CAMERA("Warning: The camera is currently idle; no need to abort.");
       return;
    }

    sendCameraCommand("abort_290");
    LOG_CAMERA("Abort command has been sent.");
    //hwStatus.cameraState = Idle;
    currentPhase = PHASE_IDLE;
    progressTimer->stop();
    ui->ExposureprogressBar->setValue(0);
    ui->labelProgressStatus->setText("Aborted");

    // 重置样式
    ui->ExposureprogressBar->setStyleSheet("");

    updateCameraControls(false);

    // 重置循环状态
    static int currentLoop = 0;
    currentLoop = 0;

}
void MainWindow::on_btnPowerDown_clicked()  {
    //LOG_GENERAL("相机下电函数被调用");
    sendCameraCommand("camera_pwr_off");
    LOG_CAMERA("Camera power-off command has been sent.");
}
void MainWindow::on_btnPowerOn_clicked()  {
    //LOG_GENERAL("相机上电函数被调用");
    sendCameraCommand("camera_pwr_on");
    LOG_CAMERA("Camera power-on command has been sent.");
}
void MainWindow::on_btnShutterOff_clicked()  {
    sendCameraCommand("io_set_shutter:0");
    LOG_CAMERA("Shutter off command has been sent");
}
void MainWindow::on_btnShutterOn_clicked()  {
    sendCameraCommand("io_set_shutter:1");
    LOG_CAMERA("Shutter on command has been sent");
}
void MainWindow::on_btnCameraPowerOff_clicked()  {
    sendCommandToMCU("io_camera_off");
    modifyCameraStatusFile(false);  // false表示设置为0
    LOG_CAMERA("IO Camera power-off command has been sent.");
}
void MainWindow::on_btnCameraPowerOn_clicked()  {
    sendCommandToMCU("io_camera_on");
    modifyCameraStatusFile(false);  // false表示设置为0
    LOG_CAMERA(" IO Camera power-oN command has been sent.");
}
void MainWindow::on_btnHeatPowerOff_clicked()  {
    sendCommandToMCU("io_heating_off");
    LOG_GENERAL("Heating power-off command has been sent.");
}
void MainWindow::on_btnHeatPowerOn_clicked()  {
    sendCommandToMCU("io_heating_on");
    LOG_GENERAL("Heating power-on command has been sent");
}
void MainWindow::on_btnVaccuPowerOff_clicked()  {
    sendCommandToMCU("io_vaccu_off");
    LOG_GENERAL("Vaccu power-off command has been sent");
}
void MainWindow::on_btnVaccuPowerOn_clicked()  {
    sendCommandToMCU("io_vaccu_on");
    LOG_GENERAL("Vaccu power-on command has been sent");
}
void MainWindow::on_btnReadIOStatus_clicked()  {
    sendCommandToMCU("io_status_read");
    LOG_GENERAL("已发送io_status_read指令");
}


void MainWindow::on_btnSetFitsPath_clicked()
{
    QString path = QFileDialog::getExistingDirectory(
        this,
        "Choose The FITS saving path",
        fitsSavePath.isEmpty() ?
            QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) :
            fitsSavePath
        );

    if (!path.isEmpty()) {
        fitsSavePath = path;
        ui->lineEditFitsPath->setText(fitsSavePath);
        LOG_GENERAL("The FITS saving path has been set to: " + fitsSavePath);
    }
}

void MainWindow::on_btnbin2fits_clicked(){
    //binPath = "/home/csst/PS_mosaic/data/bin_tmp";
    QString binFile = "/home/shenxiuqi/Documents/debug.bin";
    QString fitsFile = "debug_00.fits";

    // 使用C++转换
    if (convertBinToFits(binFile, "/home/shenxiuqi/Documents/debug", "cpp")) {
        LOG_GENERAL("转换成功: " + fitsFile);
    } else {
        LOG_GENERAL("转换失败: " + binFile);
    }
}

// 开始序列拍摄
void MainWindow::on_btnStartSequence_clicked()
{
    // 检查相机是否就绪
    if (cameraState.status != 0) {
        QMessageBox::warning(this, "警告", "相机当前忙，无法开始序列拍摄");
        return;
    }

    // 检查FITS路径是否设置
    if (fitsSavePath.isEmpty()) {
        QMessageBox::warning(this, "警告", "请先设置FITS文件保存路径");
        return;
    }

    // 选择配置文件
    QString configFile = QFileDialog::getOpenFileName(
        this,
        "选择拍摄序列配置文件",
        QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation),
        "Text Files (*.txt)"
        );

    if (configFile.isEmpty()) return;

    // 读取配置文件
    QFile file(configFile);
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QMessageBox::critical(this, "错误", "无法打开配置文件: " + file.errorString());
        return;
    }

    sequenceTasks.clear();
    QTextStream in(&file);

    // 读取第一行作为序列名称
    if (!in.atEnd()) {
        currentSequenceName = in.readLine().trimmed();
    }

    // 读取任务
    int lineNum = 1;
    while (!in.atEnd()) {
        LOG_GENERAL(QString("当前读取配置文件: 第%1行").arg(lineNum));
        lineNum++;
        QString line = in.readLine().trimmed();

        LOG_GENERAL("loaded: "+line);

        if (line.isEmpty()) continue;

        // QStringList parts = line.split('\t');
        // QStringList parts = line.split(QRegExp("\s+"),QString::SkipEmptyParts);
        QStringList parts = line.simplified().split(" ");  // handle both space and tab seperators
        if (parts.size() < 5) {
            LOG_GENERAL(QString("警告: 第%1行格式不正确，已跳过").arg(lineNum));
            continue;
        }

        SequenceTask task;
        task.filename = parts[0].trimmed();
        task.expTime = parts[1].toDouble();
        task.dark = parts[2].toInt() != 0;
        task.pinning = parts[3].toInt() != 0;
        task.dump = parts[4].toInt() != 0;

        LOG_GENERAL(QString("==> loaded expTime: %1 s").arg(task.expTime));

        // 验证数据
        if (task.filename.isEmpty() || task.expTime < 0) {
            LOG_GENERAL(QString("警告: 第%1行参数无效，已跳过").arg(lineNum));
            continue;
        }

        sequenceTasks.append(task);
        LOG_GENERAL(QString("当前sequenceTasks size : %1").arg(sequenceTasks.size()));
    }

    file.close();

    if (sequenceTasks.isEmpty()) {
        QMessageBox::warning(this, "警告", "配置文件中没有有效的拍摄任务");
        return;
    }

    // 开始序列
    currentSequenceIndex = -1;
    isSequenceRunning = true;
    ui->btnStartSequence->setEnabled(false);
    ui->btnStopSequence->setEnabled(true);

    ui->btnStartExposure->setEnabled(false);

    LOG_GENERAL(QString("开始连续拍摄序列 [%1]，共%2个任务").arg(currentSequenceName).arg(sequenceTasks.size()));
    processSequenceNextFrame();
}

void MainWindow::on_btnStopSequence_clicked()
{
    if (isSequenceRunning) {
        isSequenceRunning = false;
        m_sequenceAborted = true;
        ui->btnStartSequence->setEnabled(true);
        ui->btnStopSequence->setEnabled(false);

        ui->btnStartExposure->setEnabled(true);
        //ui->labelSequenceProgress->setText("正在停止序列...");
        progressTimer->stop();
        LOG_CAMERA(QString("用户请求停止序列 [%1]，将在当前任务完成后停止").arg(currentSequenceName));
    }
}

void MainWindow::onCheckboxShowFitsToggled(bool checked)
{
    //ui->lineEditFitsFile->setEnabled(checked);
    //ui->pushBtnFitsFile->setEnabled(checked);

    // 取消勾选时关闭已打开的DS9窗口
    if(!checked && !ds9Process.isNull()) {
        ds9Process->terminate();
    }
}

void MainWindow::checkCameraConnectionStatus()
{
    qint64 currentTime = QDateTime::currentMSecsSinceEpoch();
    const qint64 timeout = 1500; // 1.5秒超时

    // 检查主板状态
    bool masterConnected = (currentTime - m_lastStatusTime["master"] <= timeout);
    updateMasterLedStatus(masterConnected);

    // 检查从板状态
    for (int i = 0; i < 4; ++i) {
        QString slaveId = QString("%1").arg(i);
        bool slaveConnected = (currentTime - m_lastStatusTime[slaveId] <= timeout) &&
                              m_slaveBoardStatus[slaveId];

        // 更新从板指示灯
        QString style = slaveConnected ?
                            "background-color: green; border-radius: 12px;" :
                            "background-color: red; border-radius: 12px;";

        statusLeds.slave[i].led->setStyleSheet(style);
    }
}

void MainWindow::onSequenceFinished()
{
    // 序列完成后重置状态，允许开始新序列
    ui->btnStartSequence->setEnabled(true);
    ui->btnStopSequence->setEnabled(false);
    //ui->labelSequenceProgress->setText("序列已完成");

    // 询问是否开始新序列
    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, "序列完成", "当前序列已完成，是否开始新序列?",
                                  QMessageBox::Yes|QMessageBox::No);

    if (reply == QMessageBox::Yes) {
        on_btnStartSequence_clicked();
    }
}


void MainWindow::onSetTemperature()
{
    double target = ui->spinTemperature_2->value();
    hwStatus.targetTemp = target;
    hwStatus.isCooling = true;

    sendCommandToMCU(QString("temp_set:%1").arg(target));

    LOG_GENERAL(QString("Temperature set to: %1 °C").arg(target));
    LOG_CAMERAPS("收到响应: ");
}

void MainWindow::onSendTempCommand()
{
    QString cmd = ui->tempCommandEdit->text();
    if(!cmd.isEmpty()){
        sendCommandToMCU(cmd);
    }
}

void MainWindow::processCameraResponse() {
    // qint64 elapsedSec = m_startTime.secsTo(QDateTime::currentDateTime());
    QElapsedTimer timer;
    timer.start();

    while (cameraSocket->hasPendingDatagrams()) {
        //if (elapsedSec % 5 == 0) {
        //LOG_GENERAL("相机响应处理循环运行正常");
        //
        QByteArray datagram;
        datagram.resize(cameraSocket->pendingDatagramSize());
        QHostAddress sender;
        quint16 senderPort;

        cameraSocket->readDatagram(datagram.data(), datagram.size(), &sender, &senderPort);
        QString response = QString::fromUtf8(datagram).trimmed();
        //LOG_CAMERA("Received a response: " + response);

        // 分类处理响应
        if (response.startsWith("camera_status:")) {
            // 更新主板状态时间戳
            m_lastStatusTime["master"] = QDateTime::currentMSecsSinceEpoch();
            handleStatusResponse(response);
        }
        else if (response.startsWith("get_frame_290:$tag=")) {
            LOG_CAMERA("Received a header info response " + response);
            processCameraHeader(response);
        }
        else if (response.startsWith("get_frame_290:done=")) {
            firstdoneflag += 1;
            LOG_CAMERA("Received a get frame done response " + response);
            LOG_CAMERA(QString("firstdoneflag:  %1").arg(firstdoneflag));
            if (firstdoneflag == 1) {
                LOG_CAMERA("FIRST 290 DONE RESPONSE  ");
                // 使用QTimer延迟1秒执行handleFrameDone
                QTimer::singleShot(1500, this, [this, response]() {
                    LOG_CAMERA(QString("==> Delayed processing for: %1").arg(response));
                    handleFrameDone(response);
                });
                LOG_CAMERA(QString("==> start new process for: %1").arg(response));
            } else {
                handleFrameDone(response);
                LOG_CAMERA(QString("==> start new process for: %1").arg(response));
            }
            if (firstdoneflag == 4){
                LOG_CAMERA("firstdoneflag SET 0");
                firstdoneflag = 0;
            }
        }
        else if (response.startsWith("readout_rate_290=$")) {
            LOG_CAMERA("Received ReadoutRate response: " + response);
            handleReadoutRateResponse(response);
        }
        else if (response.startsWith("ccd_status:")) {
            // 提取从板ID (格式: ccd_status:ID=00$ready=1)
            QString idStr = response.mid(response.indexOf("ID=")+3, 1);
            if (m_lastStatusTime.contains(idStr)) {
                m_lastStatusTime[idStr] = QDateTime::currentMSecsSinceEpoch();
                m_slaveBoardStatus[idStr] = (response.contains("ready=1"));
            }
            processSlaveStatus(response);
        }
        else if (response.startsWith("camera_log:")) {
            LOG_CAMERAPS("收到响应: " + response);
        }
    }

    std::cout << QString("Function: %1 took: ").arg(__func__).toStdString() << timer.elapsed() << " milliseconds\n";
}
